//
//  Person_KVO.m
//  利用runtime创建KVO
//
//  Created by 马文星 on 16/6/13.
//  Copyright © 2016年 Demos. All rights reserved.
//

#import "Person_KVO.h"
#import <objc/runtime.h>

@implementation Person_KVO

-(void)setAge:(int)age{
    [super setAge:age]; //修改了子类的值后，父类的值也修改了
    [self observeChange:@"age"];
}

- (void)setName:(NSString *)name {
    [super setName:name];
    [self observeChange:@"name"];
}

- (void)observeChange:(NSString *)keypath {
    //调用KVO
    //获取观察者
    id observer = objc_getAssociatedObject(self, @"observer");
    self.delegate = observer;
    SEL selector = @selector(ml_observeValueForKeyPath:ofObject: change: context:);
    if ([self.delegate respondsToSelector:selector]) {
        //调用观察者的方法
        //就是验证手写KVO的方法  observer其实这个VC中的self
        [self.delegate ml_observeValueForKeyPath:keypath ofObject:self change:nil context:nil];
    }
}

@end
